package com.ukao.steward.ui.valetRunners.createOrder;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ukao.steward.R;
import com.ukao.steward.adapter.ClothingListAdapter;
import com.ukao.steward.adapter.PayListAdapter;
import com.ukao.steward.base.MvpFragment;
import com.ukao.steward.bean.MercCityBean;
import com.ukao.steward.bean.OrderDetailBean;
import com.ukao.steward.bean.OrderInfoBean;
import com.ukao.steward.bean.ReceiptBean;
import com.ukao.steward.bean.StringBean;
import com.ukao.steward.bean.TradeOrderBean;
import com.ukao.steward.dialog.TransNoDialogFragment;
import com.ukao.steward.dialog.UnTakeDialogFragment;
import com.ukao.steward.eventbus.MainEvent;
import com.ukao.steward.eventbus.PayEvent;
import com.ukao.steward.listener.DialogSubmitListener;
import com.ukao.steward.pesenter.valetRunners.CreateOrderPesenter;
import com.ukao.steward.printer.BluetoothPrintHelper;
import com.ukao.steward.printer.PrintMiuiHelper;
import com.ukao.steward.ui.main.HomeFragment;
import com.ukao.steward.ui.main.MainActivity;
import com.ukao.steward.ui.valetRunners.waitingOrder.OrderdetailFragment;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.DecimalUtil;
import com.ukao.steward.util.T;
import com.ukao.steward.util.Utils;
import com.ukao.steward.view.valetRunners.CreateOrderView;

import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.ukao.steward.R.id.check_balance_layout;
import static com.ukao.steward.R.id.commit_btn;
import static com.ukao.steward.R.id.commit_layout;
import static com.ukao.steward.R.id.gathering_btn;
import static com.ukao.steward.R.id.name_phone;
import static com.ukao.steward.R.id.receipt_btn;


public class CreateOrderFragment extends MvpFragment<CreateOrderPesenter> implements CreateOrderView {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.title_layout)
    RelativeLayout titleLayout;

    @BindView(R.id.orderNo)
    TextView orderNo;
    @BindView(R.id.business)
    TextView business;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.orderPrice)
    TextView orderPrice;
    @BindView(R.id.carriage)
    TextView carriage;
    @BindView(R.id.checkBox)
    AppCompatCheckBox checkBox;
    @BindView(check_balance_layout)
    LinearLayout checkBalanceLayout;
    @BindView(R.id.pay_state_hite)
    TextView payStateHite;
    @BindView(R.id.pay_state)
    TextView payState;
    @BindView(R.id.PaymentPrice)
    TextView PaymentPrice;
    @BindView(R.id.userRemark)
    EditText userRemark;

    Unbinder unbinder;
    @BindView(R.id.carriage_msg)
    TextView carriageMsg;
    @BindView(R.id.clothCnt)
    TextView clothCnt;
    @BindView(R.id.trans_no)
    TextView transNo;


    @BindView(R.id.pay_recycler_view)
    RecyclerView payRecyclerView;
    @BindView(R.id.gathering_btn)
    Button gatheringBtn;
    @BindView(R.id.business_layout)
    LinearLayout businessLayout;
    @BindView(receipt_btn)
    TextView receiptBtn;
    @BindView(R.id.name_phone)
    TextView namePhone;
    @BindView(R.id.commit_btn)
    Button commitBtn;
    @BindView(R.id.commit_layout)
    LinearLayout commitLayout;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    ArrayList<StringBean> mClothlist;
    private String takeAddressId, userId, createCnt, strbusiness, payablePrice, phone, name;
    private String service;
    private ClothingListAdapter mClothingListAdapter;
    private String clototalAmount;
    private String strcarriage = "0.00";
    private String orderId = "";
    private JSONArray mPriceDescArray;
    private OrderInfoBean mOrderInfoBean;
    private PayListAdapter mPayListAdapter;
    private List<TradeOrderBean.ListBean> mTradeOrderData = new ArrayList<>();
    private int couponAmt = 0;
    private boolean isValuationEnter;
    private OrderDetailBean mOrderDetailBean;
    private boolean isChageSucceed = false;
    boolean isCarriageSucceed = false;  /*取送费加载成功*/
    private boolean isStorageEnter;
    private boolean isOrderStockInEnter;

    /**
     * @param takeAddressId 地址id
     * @param userId        用户
     * @param createCnt     数量
     * @param business      tab id
     * @param proPriceDesc  衣物列表
     * @param payablePrice  支付价格
     * @param service       选择服务
     * @param phone         下单人手机号
     * @param name          下单人名称
     * @param isStorageEnter  是否是入库下单
     * @return
     */
    public static CreateOrderFragment newInstance(String takeAddressId, String userId, String createCnt,
                                                  String business, ArrayList<StringBean> proPriceDesc, String payablePrice, String service,
                                                  String phone, String name,boolean  isStorageEnter) {
        CreateOrderFragment fragment = new CreateOrderFragment();
        Bundle args = new Bundle();
        args.putString("takeAddressId", takeAddressId);
        args.putString("userId", userId);
        args.putString("createCnt", createCnt);
        args.putString("business", business);
        args.putParcelableArrayList("proPriceDesc", proPriceDesc);
        args.putString("payablePrice", payablePrice);
        args.putString("service", service);
        args.putString("phone", phone);
        args.putString("name", name);
        args.putBoolean("isStorageEnter", isStorageEnter);

        fragment.setArguments(args);
        return fragment;
    }


    /**
     * 快速下单
     *
     * @param takeAddressId 地址id
     * @param userId        用户id
     * @param createCnt     订单数量
     * @param payablePrice  支付价格
     * @param phone         下单人手机号
     * @param name          下单人名称
     * @return
     */
    public static CreateOrderFragment newInstance(String takeAddressId, String userId, String createCnt,
                                                  String payablePrice,
                                                  String phone, String name ) {
        CreateOrderFragment fragment = new CreateOrderFragment();
        Bundle args = new Bundle();
        args.putString("takeAddressId", takeAddressId);
        args.putString("userId", userId);
        args.putString("createCnt", createCnt);
        args.putString("payablePrice", payablePrice);
        args.putString("phone", phone);
        args.putString("name", name);
        fragment.setArguments(args);
        return fragment;
    }


    /**
     * @param createCnt        数量
     * @param payablePrice     支付价格
     * @param proPriceDesc    衣物列表
     * @param isValuationEnter 是否是精准计价进入
     * @return
     */
    public static CreateOrderFragment newInstance(OrderDetailBean mOrderDetailBean, String createCnt,
                                                  String payablePrice,
                                                  ArrayList<StringBean> proPriceDesc, boolean isValuationEnter,boolean  isOrderStockInEnter) {
        CreateOrderFragment fragment = new CreateOrderFragment();
        Bundle args = new Bundle();
        args.putParcelable("orderDetail", mOrderDetailBean);
        args.putString("createCnt", createCnt);
        args.putString("payablePrice", payablePrice);
        args.putParcelableArrayList("proPriceDesc", proPriceDesc);
        args.putBoolean("isValuationEnter", isValuationEnter);
        args.putBoolean("isOrderStockInEnter", isOrderStockInEnter);

        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mOrderDetailBean = getArguments().getParcelable("orderDetail");
            takeAddressId = getArguments().getString("takeAddressId");
            userId = getArguments().getString("userId");
            createCnt = getArguments().getString("createCnt");
            strbusiness = getArguments().getString("business");
            mClothlist = getArguments().getParcelableArrayList("proPriceDesc");
            payablePrice = getArguments().getString("payablePrice");
            service = getArguments().getString("service");
            phone = getArguments().getString("phone");
            name = getArguments().getString("name");
            isValuationEnter = getArguments().getBoolean("isValuationEnter", false);
            isStorageEnter = getArguments().getBoolean("isStorageEnter", false);
            isOrderStockInEnter = getArguments().getBoolean("isOrderStockInEnter", false);
        }
    }

    @Override
    protected CreateOrderPesenter createPresenter() {
        return new CreateOrderPesenter(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_create_order, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
    }

    @Override
    protected void initView() {
        mvpPresenter.cityCarriage();
        titleLayout.setBackgroundColor(getColors(R.color.colorPrimary));
        if (isValuationEnter) {
            if (isOrderStockInEnter){
                setcheckBoxEnabled();
            }
            userRemark.setEnabled(false);
            title.setText(isOrderStockInEnter?"入库":"精准计价");
            commitBtn.setText(isOrderStockInEnter?"确定":"确定");
            orderNo.setText(mOrderDetailBean.getOrderNo());
            OrderDetailBean.UserInfoBean muserInfo = mOrderDetailBean.getUserInfo();
            namePhone.setText(muserInfo.getPhone() + " " + muserInfo.getName());
            transNo.setText(mOrderDetailBean.getTransNo());
            checkBox.setChecked(mOrderDetailBean.getIsFeeCarriage());
            orderId = mOrderDetailBean.getId() + "";
        } else {
            title.setText("提交订单");
        }

        initLinearRecyclerView(payRecyclerView);
        payRecyclerView.setNestedScrollingEnabled(false);
        recyclerView.setNestedScrollingEnabled(false);
        mPayListAdapter = new PayListAdapter(_mActivity, mTradeOrderData);
        payRecyclerView.setAdapter(mPayListAdapter);
        fillData();


    }

    private void setcheckBoxEnabled() {
        checkBalanceLayout.setEnabled(false);
        checkBox.setEnabled(false);
        checkBox.setButtonDrawable(R.drawable.pay_check_endle);
    }

    private void fillData() {
        clothCnt.setText(CheckUtils.isEmpty(createCnt) ? "0件" : createCnt + "件");
        if (isValuationEnter) {
            businessLayout.setVisibility(View.GONE);
        } else {
            business.setText(CheckUtils.isEmptyString(service));/*服务*/
            namePhone.setText(CheckUtils.isEmptyString(phone) + "  " + name);
        }
        if (CheckUtils.isNull(mClothlist)) {
            clototalAmount = CheckUtils.isEmpty(payablePrice) ? "0.00" : payablePrice;
            orderPrice.setText("￥" + clototalAmount); /* /*衣物总额*/
            return;
        }


        initAdapter();
        String strtotalAmount;
        clototalAmount = "0.00";
        mPriceDescArray = new JSONArray();
        if (!CheckUtils.isEmpty(mClothlist)) {
            for (StringBean stringBean : mClothlist) {
                createProPriceDescs(stringBean);
                String discounts = CheckUtils.isDiscount(stringBean.getDiscount());
                String unitPrice = CheckUtils.isEmptyNumber(stringBean.getPrice());
                if (CheckUtils.isEmpty(discounts)) {
                    strtotalAmount = DecimalUtil.multiply(stringBean.getCnt() + "", unitPrice);
                } else {
                    String discountPrice = DecimalUtil.multiply(unitPrice, CheckUtils.isEmptyNumber(stringBean.getDiscount()));
                    strtotalAmount = DecimalUtil.multiply(stringBean.getCnt() + "", discountPrice);
                }
                clototalAmount = DecimalUtil.add(clototalAmount, strtotalAmount);
            }
            orderPrice.setText("￥" + clototalAmount); /* /*衣物总额*/
        }


    }


    /**
     * 创建衣物附件
     *mercBusinessId, 项目id
     businessId, 经营大类
     businessName, 项目名称
     proTypeId, 产品类型id
     proServiceId, 产品服务项目id
     serviceName, 服务名称
     * @param stringBean
     */
    private void createProPriceDescs(StringBean stringBean) {
        JSONObject mPriceDescbject = new JSONObject();
        try {
            mPriceDescbject.put("discount", CheckUtils.isNull(stringBean.getDiscount()) ? "" : stringBean.getDiscount());
            mPriceDescbject.put("id", stringBean.getId());
            mPriceDescbject.put("name", stringBean.getName());
            mPriceDescbject.put("cnt", stringBean.getCnt());
            mPriceDescbject.put("path", CheckUtils.isEmptyString(stringBean.getPath()));
            mPriceDescbject.put("price", stringBean.getPrice());
            if (isStorageEnter||isOrderStockInEnter){
                mPriceDescbject.put("mercBusinessId", stringBean.getMercBusinessId());
                mPriceDescbject.put("businessId", stringBean.getBusinessId());
                mPriceDescbject.put("businessName", stringBean.getBusinessName());
                mPriceDescbject.put("proTypeId", stringBean.getProTypeId());
                if(!CheckUtils.isEmpty(stringBean.getSrvName())){
                    mPriceDescbject.put("proServiceId", stringBean.getSrvId());
                    mPriceDescbject.put("serviceName", stringBean.getSrvName());
                }

            }
            if (isValuationEnter && !stringBean.getSrvName().isEmpty()&&!isOrderStockInEnter) {
                mPriceDescbject.put("srvName", stringBean.getSrvName());
                mPriceDescbject.put("srvId", stringBean.getSrvId());
            }
            mPriceDescArray.put(mPriceDescbject);
        } catch (JSONException e) {


        }
    }

    private void initAdapter() {
        initLinearRecyclerView(recyclerView);
        mClothingListAdapter = new ClothingListAdapter(_mActivity, mClothlist);
        recyclerView.setAdapter(mClothingListAdapter);
    }


    @Override
    protected void initListener() {
        super.initListener();
        checkBox.setOnCheckedChangeListener(mOnCheckedListener);
    }


    private void showTransNoDialog() {
        TransNoDialogFragment.createBuilder(getChildFragmentManager())
                .orderId(orderId)
                .userRemark(getText(userRemark))
                .mListener(mDialogSubmitListener)
                .show();





    }

    private DialogSubmitListener mDialogSubmitListener = new DialogSubmitListener() {
        @Override
        public void onSubmitClick(int parent, Object message) {
           // mvpPresenter.addTransNo(orderId, (String) message, getText(userRemark));
            addTransNoSucceed((String) message);
        }
    };

    CompoundButton.OnCheckedChangeListener mOnCheckedListener = (buttonView, isChecked) ->
            reckonShouldPice(isChecked);


    @Override
    public void createOrderSucceed(String orderId) {
        this.orderId = orderId;
        setcheckBoxEnabled();
        receiptBtn.setVisibility(View.VISIBLE);
        if (!isStorageEnter) {
            mvpPresenter.payInfo(orderId);
            commitBtn.setText("录运单号");}
        if (isStorageEnter){
            OrderdetailFragment  mOrderdetailFragment=OrderdetailFragment.createBuilder()
                    .orderId(orderId)
                    .isValuation(isValuationEnter)
                    .isPopToHome(true)
                    .build();
            start(mOrderdetailFragment,SINGLETASK);
           }







    }

    /**
     * @param mMercCityBean 取送费数据
     * @param strcarriage   取送费
     */
    @Override
    public void carriageSucceed(MercCityBean mMercCityBean, String strcarriage) {
        isCarriageSucceed = true;
        String freeCarriageAmt = CheckUtils.isEmptyNumber(mMercCityBean.getFreeCarriageAmt());
        if (mMercCityBean.getFreeCarriageAmt() != 0) {
            carriageMsg.setText("取送费（满" + freeCarriageAmt + "免取送费）");
        }
        double douClototalAmount = Double.parseDouble(clototalAmount);
        double doustrcarriage = Double.parseDouble(freeCarriageAmt);
        if (douClototalAmount == doustrcarriage || douClototalAmount > doustrcarriage) {
            this.strcarriage = "0.00";
        } else {
            this.strcarriage = strcarriage;

        }
        carriage.setText("￥" + this.strcarriage);
        reckonShouldPice(checkBox.isChecked());
    }


    /**
     * 支付类型
     */
    @Override
    public void loadtradeOrder(List<TradeOrderBean.ListBean> mListBean) {
        payRecyclerView.setVisibility(View.VISIBLE);
        if (commitBtn.getVisibility() == View.GONE) {
            commitLayout.setVisibility(View.GONE);
        }

        if (couponAmt != 0) {
            TradeOrderBean.ListBean mItem = new TradeOrderBean.ListBean("优惠券抵扣", couponAmt);
            mListBean.add(0, mItem);

        }
        mPayListAdapter.setDataList(mListBean);
    }

    /**
     * 添加运单号
     */
    @Override
    public void addTransNoSucceed(String strtransNo) {

        commitBtn.setVisibility(View.GONE);
        transNo.setText(strtransNo);
        userRemark.setEnabled(false);

    }


    /**
     * 支付订单信息
     */
    @Override
    public void OrderInfoSucceed(OrderInfoBean mOrderInfoBean) {
        this.mOrderInfoBean = mOrderInfoBean;
        gatheringBtn.setVisibility(View.VISIBLE);
        orderNo.setText(mOrderInfoBean.getOrderNo());
        setcheckBoxEnabled();
        mOrderInfoBean.setClototalAmount(clototalAmount);


    }

    private void reckonShouldPice(boolean isChecked) {
        if (isChecked && checkBox.getVisibility() == View.VISIBLE) {
            PaymentPrice.setText("￥" + DecimalUtil.add(clototalAmount, strcarriage)); /*应收款*/
        } else {

            PaymentPrice.setText("￥" + clototalAmount);/*应收款*/

        }
    }


    @OnClick({R.id.back_btn, commit_btn, check_balance_layout, gathering_btn, R.id.title, receipt_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case gathering_btn:  /*收款*/
                if (CheckUtils.isNull(mOrderInfoBean)) return;

                start(PayOrderFragment.newInstance(orderId, mOrderInfoBean));


                break;

            case check_balance_layout:
                if (checkBox.getVisibility() == View.VISIBLE) {
                    if (checkBox.isChecked()) {
                        checkBox.setChecked(false);
                    } else {
                        checkBox.setChecked(true);
                    }
                }


                break;

            case R.id.back_btn:

                closeOtherFragment();

                break;
            case commit_btn:
                /*获取取送费成功*/
                if (isCarriageSucceed) {
                    if (getText(commitBtn).equals("提交订单")) {
                        mvpPresenter.createOrderRuquest(mPriceDescArray,
                                strbusiness, userId, takeAddressId, createCnt, clototalAmount, checkBox.isChecked(), strcarriage,isStorageEnter);
                    } else if (isValuationEnter) {
                        if (!isOrderStockInEnter){
                            mvpPresenter.valuationAccurate(orderId, createCnt, mPriceDescArray, clototalAmount, getText(userRemark), checkBox.isChecked(), strcarriage);
                        }else{
                            mvpPresenter.orderStockIn(orderId,mPriceDescArray.toString());
                        }

                    } else {


                        showTransNoDialog();
                    }
                } else {
                    mvpPresenter.cityCarriage();
                }


                break;
            case receipt_btn:  /*打印小票*/

                mvpPresenter.printReceipt( orderId);


                break;


        }
    }


    @Override
    protected boolean useEventBus() {
        return true;
    }


    @Subscribe
    public void onEvent(PayEvent event) {
        switch (event.getMessage()) {
            case PAY_FINISG:
                mOrderInfoBean = (OrderInfoBean) event.getData();
                OrderInfoBean.UPayCardBean uPayCard = mOrderInfoBean.getUPayCard();
                if (!CheckUtils.isNull(uPayCard) && uPayCard.getUseCoupon() && mOrderInfoBean.isUseUPay()) {
                    couponAmt = mOrderInfoBean.getCouponAmt();
                }
                gatheringBtn.setVisibility(View.GONE);
                payState.setBackgroundResource(R.drawable.shape_strok_green);
                payState.setTextColor(getColors(R.color.green));
                payState.setText("已付款");
                mvpPresenter.tradeOrder(orderId);
                break;

        }
    }

    @Override
    public boolean onBackPressedSupport() {
        closeOtherFragment();

        return true;
    }

    private void closeOtherFragment() {
        try{
            if (!isAdded())return;
            CreateOrderFragment  mOrderFragment=findFragment(CreateOrderFragment.class);
            if (mOrderFragment!=null){
                if (!isValuationEnter && !CheckUtils.isEmpty(orderId)) {
                    popTo(HomeFragment.class,false);
                }else if (isValuationEnter && isChageSucceed) {
                    setFragmentResult(RESULT_OK, null);
                    finish();
                } else {
                    finish();
                }
            }


        }catch (Exception e){

        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();


    }


    /**
     * 计价成功
     */
    @Override
    public void valuationSucceed(String msg) {
        T.show(msg);
       if (CheckUtils.isMIUIDevices()){
           receiptBtn.setVisibility(View.VISIBLE);
       }

        setcheckBoxEnabled();
        isChageSucceed = true;
        userRemark.setEnabled(false);
        commitLayout.setVisibility(View.GONE);
    }

    @Override
    public void loadReceipt(ReceiptBean mReceiptBean) {

        if (CheckUtils.isMIUIDevices()){
            PrintMiuiHelper.receiptReceipt(MainActivity.getPrintService(),mReceiptBean );
        }else {

            BluetoothPrintHelper.receiptReceipt(_mActivity,mReceiptBean);
        }

    }

    /**
     * 订单入库
     */
    @Override
    public void orderStockInSucceed() {
     //  gatheringBtn.setVisibility(View.VISIBLE);
        setFragmentResult(RESULT_OK, null);
        finish();
        commitLayout.setVisibility(View.GONE);
        if (CheckUtils.isMIUIDevices()){
            receiptBtn.setVisibility(View.VISIBLE);
        }
        isChageSucceed = true;



    }
}
